package com.sy.olddriver.service.impl;

import com.sy.olddriver.dao.OrderDao;
import com.sy.olddriver.dao.impl.OrderDaoImpl;
import com.sy.olddriver.dto.Result;
import com.sy.olddriver.entity.Order;
import com.sy.olddriver.entity.OrderItem;
import com.sy.olddriver.entity.User;
import com.sy.olddriver.exception.OldDriverException;
import com.sy.olddriver.service.OrderService;
import com.sy.olddriver.utils.DbUtils;
import com.sy.olddriver.utils.HttpUtils;
import com.sy.olddriver.utils.JdbcHelper;
import com.sy.olddriver.utils.RandomUtils;
import com.sy.olddriver.vo.OrderItemParam;
import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * OrderService接口的实现类
 *
 * @author Administrator
 */
public class OrderServiceImpl implements OrderService {
    private OrderDao orderDao = new OrderDaoImpl();

    @Override
    public Result generateOrder(List<OrderItemParam> orderItemParams) {
        Result result = new Result();
        try {
            //先获取当前的登录用户
            User user = HttpUtils.getLoginUser();

            //生成订单表数据
            String oid = RandomUtils.generateOrderId();
            Order order = new Order();
            order.setOrderId(oid);
            order.setUid(user.getId());

            //生成订单商品表数据
            List<OrderItem> orderItems = new ArrayList<>();
            if (CollectionUtils.isEmpty(orderItemParams)) {
                throw new OldDriverException("未选择任何商品");
            }
            for (OrderItemParam orderItemParam : orderItemParams) {
                OrderItem orderItem = new OrderItem();
                orderItem.setOid(oid);
                orderItem.setPid(orderItemParam.getPid());
                orderItem.setCount(orderItemParam.getCount());
                orderItems.add(orderItem);
            }

            //将数据插入订单表和订单商品表
            //1.开启事务
            DbUtils.beginTx();
            orderDao.addOrder(order);
            orderDao.addOrderItems(orderItems);
            //2.提交事务
            DbUtils.commit();
        } catch (Exception e) {
            //3.回滚事务
            DbUtils.rollback();
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrMsg(e.getMessage());
        } finally {
            //4.关闭资源
            DbUtils.close();
        }
        return result;
    }

}
